const express = require('express');

const path = require('path');

const bodyParser = require('body-parser');//引入了配置post请求参数所需的模块

// const cookieParser = require('cookie-parser');//引入cookie模块

// const md5 = require('md5');//引入md5加密的模块

// const ObjectId = require('mongodb').ObjectId;

// const db = require('./model/db.js');//引入数据库操作的模块

// 引入session模块
var session = require('express-session');

//引入router模块
const router = require('./route/router.js');

// 持久化
// var NedbStore = require('nedb-session-store')(session);

const app = express();//构建服务器

// 配置socket.io
const http = require('http').Server(app);
const io = require('socket.io')(http);

let allUser = [];

//模板引擎的配置
app.engine('art', require('express-art-template'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'art');
//开放静态资源
app.use(express.static(path.join(__dirname, 'public')));
// 处理post请求参数
app.use(bodyParser.urlencoded({ extended: false }));

// 配置cookie
// app.use(cookieParser());
// 配置session
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: {
        // 设置存在时长  ms
        maxAge: 300000
    }
}));

app.get('/',router.showIndex);

app.post('/login', router.login);

app.post('/register', router.regit);

app.get('/query', router.query);

app.get('/publish', router.publish);

app.get('/remark', router.remark);

app.get('/others', router.others);

app.get('/remove',router.remove)
//聊天室部分
app.get('/chatroom',(req,res) => {
    if(req.session.user){
        res.render('chat',{
            uname: req.session.user,
            num:allUser.length,
            user:allUser
        });
    }else{
        res.send("您尚未登录，请登录后再访问该地址");
    }
})
// 配置长连接
io.on('connection',(socket) =>{
    //接收客户端数据
    socket.on('chat',(msg) => {
        // console.log(msg);
        // 发送数据给客户端
        io.emit('send',msg);
    });
    socket.on('login',(msg) => {
        if(allUser.includes(msg.uname)){
            return false;
        }
        allUser.push(msg.uname);
        msg.num = allUser.length;//有用户加入了聊天室，需要广播当前在聊天室的人数
        msg.user = allUser;//广播有哪些用户在线
        io.emit('login',msg);
    });
    socket.on('disconnect1',(msg)=>{
        var index = allUser.indexOf(msg.uname);
        // console.log(msg.uname);
        allUser.splice(index,1);
        msg.num = allUser.length;//有用户退出聊天室后，需要广播当前在聊天室的人数
        msg.user = allUser;//广播有哪些用户在线
        io.emit('disconnect2',msg);
    });
});

http.listen(80,'192.168.1.102',() => {
    console.log('服务器启动成功');
})
// app.listen(3000, () => {
//     console.log('服务器启动成功');
// });